<?php
/**
 * Created by PhpStorm.
 * User: mojie126
 * Date: 2017/5/26 0026
 * Time: 下午 15:53
 */

namespace app\index\controller;

use app\common\imdb;
use app\index\common\logchecker\RipLogChecker;
use Bhutanio\BEncode\BEncode;
use think\Session;
use think\Validate;

class ReleaseController extends Base
{
	public function index()
	{
		$this->assign("title", "发布");
		$where = [
			"display" => ["=", "0"],
			"pid" => ["=", "0"]
		];
		$res = db("category")->where($where)->order("sort", "DESC")->select();
		$this->assign("olcate", $res);//olcate = One Level Category
		$info = db("information")->select();
		$this->assign("info", $info);
		$info = db("container")->select();
		$this->assign("container", $info);
		$info = db("resolution")->select();
		$this->assign("resolution", $info);
		$info = db("source")->select();
		$this->assign("source", $info);
		$this->getAccess();

		return $this->fetch();
	}

	public function getDouBan($wd)
	{
		$douban = json_decode(mycurl("http://huancun.org/ajax_getinfo.php", "wd=$wd", 1));
		$descs = preg_replace("/(https?.*)(jpg|jpeg|png|gif)/i", "<img src='$1$2' />", $douban->ss);

		return $descs;
	}

	public function doRelease()
	{
		$info = input("param.");

		//输入验证
		$rule = [
			"olcate|分类" => "require|notIn:0",
			"slcate|二级分类" => "require|notIn:0",
			"maintitle|主标题" => "require",
			"descs|详情" => "require",
			"__token__" => "require|token"
		];
		$msg = [
			"__token__" => "请勿重复提交"
		];
		$data = [
			"olcate" => $info['olcate'],
			"slcate" => $info['slcate'],
			"maintitle" => $info['maintitle'],
			"descs" => $info['descs'],
			"__token__" => $info['__token__']
		];
		$validate = new Validate($rule, $msg);
		$check = $validate->check($data);
		if (!$check) {
			$this->error($validate->getError(), "/index/release");
		}
		//输入验证

		$torrent = request()->file("torrent");
		$torrents = $torrent->validate(["ext" => "torrent"])->rule("md5")->move(ROOT_PATH . "public" . DS . "torrents");
		$torrentfile = ROOT_PATH . "public" . DS . "torrents" . DS . $torrents->getSaveName();
		$bcode = new BEncode();
		$bcode->set([
			"announce" => getWebURL() . "/announce",
			"comment" => APP_NAME,
			"created_by" => APP_NAME
		]);
		$dict = $bcode->bdecode_file($torrentfile);
		$dict['info']['source'] = APP_NAME;
		$file = $bcode->filelist($dict);
		$dicts = $bcode->make_private($dict);
		$infohash = sha1($bcode->bencode($dicts['info']));
		$bininfohash = pack("H*", sha1($bcode->bencode($dicts['info'])));
		$fp = fopen($torrentfile, "w");
		$finish = 0;
		if ($dict && $fp) {
			fwrite($fp, $bcode->bencode($dicts));
			fclose($fp);
			$checkonly = db("movie")->where("infohash", $infohash)->field("type")->union(function ($query) use ($infohash) {
				$query->name("series")->where("infohash", $infohash)->field("type");
			})->select();
			if (!$checkonly) {
				$finish = 1;
			} else {
				$this->error("该种子已经存在", "/index/release");
			}
		} else {
			unset($torrents);
			unlink($torrentfile);
			$this->error("Waht Are You 弄啥嘞？！", "/index/release");
		}
		$imdburl = isset($info['imdburl']) ? $info['imdburl'] : "";
		$doubanurl = isset($info['doubanurl']) ? $info['doubanurl'] : "";
		if (!empty($imdburl)) {
			$imdbrating = imdb::getIMDbRating($imdburl);
		} else {
			$imdbrating = "";
		}
		$sticktime = "";
		$discounttime = "";
		if ($this->checkAccess(1)) {
			if (!empty($info['sticklevel']) && isset($info['sticktime'])) {
				if ($info['sticktime'] == "") {
					$sticktime = date("Y-m-d H:i:s", time() + 6 * 3600);
				} elseif ($info['sticktime'] == 0) {
					$sticktime = "";
				} else {
					$sticktime = date("Y-m-d H:i:s", time() + $info['sticktime'] * 3600);
				}
			}
			if (!empty($info['discount']) && isset($info['discounttime'])) {
				if ($info['discounttime'] == "") {
					$discounttime = date("Y-m-d H:i:s", time() + 6 * 3600);
				} elseif ($info['discounttime'] == 0) {
					$discounttime = "";
				} else {
					$discounttime = date("Y-m-d H:i:s", time() + $info['discounttime'] * 3600);
				}
			}
		}
		if ($torrents && $finish == 1) {
			$save = [
				"infohash" => $infohash,
				"bininfohash" => $bininfohash,
				"torrentfiles" => $file['file_count'],
				"torrentsize" => $file['total_size'],
				"torrentpath" => $torrents->getSaveName(),
				"addtime" => date("Y-m-d H:i:s", time()),
				"uploader" => Session::get("uid"),
				"maintitle" => $info['maintitle'],
				"subtitle" => $info['subtitle'],
				"descs" => $info['descs'],
				"olcate" => $info['olcate'],
				"slcate" => isset($info['slcate']) ? $info['slcate'] : "1",
				"doubanurl" => $doubanurl,
				"imdburl" => $imdburl,
				"imdbscore" => $imdbrating,
				"anonymous" => isset($info['anonymous']) ? $info['anonymous'] : "",
				"author" => isset($info['author']) ? $info['author'] : "",
				"sticklevel" => isset($info['sticklevel']) ? $info['sticklevel'] : "",
				"sticktime" => $sticktime,
				"discount" => isset($info['discount']) ? $info['discount'] : "",
				"discounttime" => $discounttime
			];
			if ($this->checkAccess(1)) {
				$save = array_merge($save, [
					"official" => isset($info['official']) ? $info['official'] : "",
					"excl" => isset($info['excl']) ? $info['excl'] : "",
					"first" => isset($info['first']) ? $info['first'] : "",
					"hr" => isset($info['hr']) ? $info['hr'] : ""
				]);
			}
			if ($info['olcate'] == 3) {
				$save = array_merge($save, ["logscore" => isset($info['logscore']) ? $info['logscore'] : ""]);
			}
			if ($info['olcate'] != 1) {
				//存入series表
				//输入验证
				$rule = [
					"subtitle|季集名称" => "require",
					"albumname|聚合名称" => "require",
					"container|容器类型" => "require",
					"source|获取源类型" => "require",
					"resolution|分辨率" => "require"
				];
				$data = [
					"subtitle" => $info['subtitle'],
					"albumname" => $info['albumname'],
					"container" => $info['container'],
					"source" => $info['source'],
					"resolution" => $info['resolution']
				];
				$validate = new Validate($rule);
				$check = $validate->check($data);
				if (!$check) {
					$this->error($validate->getError(), "/index/release");
				}
				//输入验证
				$save = array_merge($save, [
					"albumname" => isset($info['albumname']) ? preg_replace("/[\/\\\]/", "", $info['albumname']) : "",
					"container" => isset($info['container']) ? $info['container'] : "",
					"source" => isset($info['source']) ? $info['source'] : "",
					"resolution" => isset($info['resolution']) ? $info['resolution'] : ""
					//其他需要存的项目
				]);
				$id = db("series")->insertGetId($save);
				$this->success("发布成功，请重新下载种子文件并持续做种", "/series/id/$id&n");
			} else {
				//存入movie表
				$id = db("movie")->insertGetId($save);
				$this->success("发布成功，请重新下载种子文件并持续做种", "/movie/id/$id&n");
			}
		} else {
			unset($torrents);
			unlink($torrentfile);
			$this->error("种子文件不是常规格式", "/index/release");
		}
	}

	public function queryTwoLevelCategory($olcate)
	{
		$where = [
			"display" => ["=", "0"],
			"pid" => ["=", $olcate]
		];
		$res = db("category")->where($where)->order("sort", "DESC")->select();
		if ($res) {
			jsonReturn(1, "", $res);
		} else {
			jsonReturn(0, "获取二级分类失败或没有二级分类");
		}
	}

	public function queryAlbum($searchalbumname)
	{
		$check = db("series")->where("albumname", $searchalbumname)->value("albumname");
		if ($check) {
			jsonReturn(1, "", $check);
		} else {
			jsonReturn(0, "未找到匹配的聚合名称");
		}
	}

	public function getLogCheckerScore($log)
	{
		$logChecker = new RipLogChecker($log);
		if (!empty($logChecker->getScore())) {
			jsonReturn(1, "", ["logscore" => $logChecker->getScore()]);
		} else {
			jsonReturn(0, "", ["logscore" => "0"]);
		}
	}
}